#include "platformAPI.h"
#include "server_input_task.h"
#include <string.h>
#include "iotgo_service.h"
#include "relay_output.h"
#include "myRTC.h"

#include <stdio.h>

#define tskServerInput_PRIORITY (tskIDLE_PRIORITY + 9)
#define READ_BUF_LEN 500

static xTaskHandle server_input_task; 

static int8_t *read_buf = NULL;

static void serverInputThread(void *parameter)
{
    int8_t error = IOTGO_ERROR_NONE;
    int8_t data_type = IOTGO_DATA_TYPE_NONE;
    int8_t iotgo_state = IOTGO_IDLE;
    
    uint8_t sequence[14] = {0};
    int32_t ret = -1;
    int8_t first_update_is_not_done = 1;

    read_buf = os_malloc(READ_BUF_LEN);
    if(read_buf == NULL)
    {
	printf("[%s] os_malloc failed!!!\n",__FUNCTION__);
    }
    
    while(read_buf != NULL)
    {
        /*step1: start data service */
        ret = iotgoDataServiceRuntime();

        iotgo_state = iotgoGetState();
        if(iotgo_state == IOTGO_REGISTER_IS_READY)
        {
            /* check the switch command*/
            ret = iotgoReadByDataType(IOTGO_DATA_TYPE_UPDATE,sequence,read_buf);
            if(ret == 0)
            {
                printf("get update\n");
                printf("data is %s\n",read_buf);
                relayUpdateByRemote(sequence,read_buf);
                //updateTimerList(sequence,read_buf);
            }

            /* check the upgrade command*/
            ret = iotgoReadByDataType(IOTGO_DATA_TYPE_UPGRADE,sequence,read_buf);
            if(ret == 0)
            {
                printf("get upGrade query");
                printf("data is %s\n",read_buf);
                //iotgoUpgrade(sequence,read_buf);
//                startUpgradeTask(sequence,read_buf);
            }

            /* check the date query return*/
            ret = iotgoReadByDataType(IOTGO_DATA_TYPE_DATE,sequence,read_buf);
            if(ret == 0)
            {
                printf("get date\n");
                printf("date is \n%s\n",read_buf);
                //updateGMTfromServer(sequence,read_buf);
                //updateDateFromServer(read_buf);
            }
            
            if(first_update_is_not_done)
            {
//                updateRelayStateToRemote();
                first_update_is_not_done = 0;
            }
            
            memset(read_buf,0,READ_BUF_LEN);
        }
    }// while(1)
}

int startServerInputTask(void)
{
    char ret = -1;
    /*step1 : create the task*/
    if(xTaskCreate(serverInputThread, 
		   ((const char*)"serverInputThread"), 
		   2000, 
		   NULL,
		   tskServerInput_PRIORITY,
		   &server_input_task) != pdPASS)
    {	
        printf("create server input thread failed\n");
	return -1;
    }
    return 0;
}

int stopServerInputTask(void)
{
    /*if there's enough ram, no need to stop this task*/
    os_free(read_buf);
    vTaskDelete(server_input_task);
    return 0;
}



